package com.leyou.gateway.filters;

import com.leyou.common.auth.JwtUtils;
import com.leyou.common.auth.Payload;
import com.leyou.common.auth.UserInfo;
import com.leyou.common.constants.UserTokenConstants;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    private JwtProperties prop;

    @Autowired
    private FilterProperties filterProp;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 过滤器类型，包括：pre、route、post、error
     *
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER + 1;
    }

    /**
     * 判断当前过滤器是否加入到过滤器链
     *
     * @return true: 要参与过滤，run方法会执行。 false：不参与过滤，run方法不执行
     */
    @Override
    public boolean shouldFilter() {
        // 1.获取Request
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        // 2.判断是否符合白名单的规则
        boolean boo = isAllowRequest(request);
        return !boo;
    }

    private boolean isAllowRequest(HttpServletRequest request) {
        // 1.得到当前请求路径
        String path = request.getRequestURI();
        // 2.得到当前请求的方式
        String method = request.getMethod().toUpperCase();
        // 3.遍历白名单规则，判断是否符合
        Map<String, String> map = filterProp.getAllowPathMap();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String pathPrefix = entry.getKey();
            String allowMethod = entry.getValue();
            if (StringUtils.startsWith(path, pathPrefix) && (allowMethod.equals("*") || method.equals(allowMethod))) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        // 1.获取Request
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        try {
            // 2.获取请求中的token
            String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
            // 3.利用公钥验证token：配置公钥，加载公钥
            Payload<UserInfo> payload = null;
            try {
                payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
            } catch (Exception e) {
                // token解析失败，无效token，拦截
                throw new RuntimeException("无效token！", e);
            }
            // 4.验证黑名单
            //	4.1.获取id
            String id = payload.getId();
            //	4.2.redis的黑名单中，没有这个token
            Boolean isExists = redisTemplate.hasKey(id);
            if (BooleanUtils.isTrue(isExists)) {
                // 无效token,拦截
                throw new RuntimeException("无效token！");
            }
            UserInfo user = payload.getUserInfo();

            log.info("登录校验成功，用户{}, 正在访问{}资源", user.getId(), request.getRequestURI());
        } catch (RuntimeException e) {
            log.error("登录校验失败，{}", e.getMessage(), e);
            // 5.验证不通过，拦截
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
        }
        //	验证通过，放行
        return null;
    }
}
